import 'dart:convert';

import 'package:example_example/pages/view/ItemToDoTaskView.dart';
import 'package:example_example/pages/view/LoadingDialog.dart';
import 'package:example_example/services/EventBus.dart';

import '../../../pages/view/LoadingView.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import '../../../global/Global.dart';
import '../../../global/GlobalUrl.dart';
import '../../../services/TLSizeFit.dart';
import '../../../util/HttpUtil.dart';
import '../../../util/LogUtil.dart';
import '../../../util/ToastUtils.dart';
import '../../../util/Storage.dart';
import '../../../pages/person/Login.dart';
import '../../view/ItemFinishTaskView.dart';
import '../../view/HeaderView.dart';
import '../../view/NoDataView.dart';
import '../../../util/TodoHttputil.dart';
import '../../../util/HttpMethod.dart';

/**刷新来自官网的demo
 * flutter_easyrefresh   刷新的第三方组件
 * https://pub.dev/packages/flutter_easyrefresh/example
 *
 * 办结任务
 *
 */

class RegularPage extends StatefulWidget {

  RegularPage({Key key}) : super(key: key);

  _RegularPageState createState() => _RegularPageState();

}

class _RegularPageState extends State<RegularPage> {

  EasyRefreshController _controller;

  // 条目总数
//  int _count = 6; //20

  List dataList = [];
  int pageIndex = 1;
  bool noDataflag = false;

  var eventBusRe;

  @override
  void initState() {
    super.initState();
    LogUtil.v("待办任务 正式立项。。。。initState");

    /**
     * 广播接收； H5审批成功后，刷新
     */
    eventBusRe =eventBus.on<ReFresshEvent>().listen((event) {
      print("3333收到了广播event:${event.reFreshFLag}");
      if(event.reFreshFLag =="3"){  // 去刷新数据
        print("333去刷新了");
        initHttpData();
      }
    });

    _controller = EasyRefreshController();
    HttpMethod.initDictionaryData(this.context);
    initHttpData();
  }

  @override
  void didChangeDependencies() {
    // TODO: implement didChangeDependencies
    super.didChangeDependencies();
    LogUtil.v("待办任务 正式立项。。。。didChangeDependencies");

  }

  @override
  void didUpdateWidget(covariant RegularPage oldWidget) {
    // TODO: implement didUpdateWidget
    super.didUpdateWidget(oldWidget);
    LogUtil.v("待办任务 正式立项。。。。didUpdateWidget");
//    initHttpData();
  }

  @override
  Widget build(BuildContext context) {
    LogUtil.v("待办任务 正式立项。。。。build");
    return Scaffold(
//        appBar: AppBar(
//          title: Text("EasyRefresh"),
//        ),
      body: Stack(
        children: <Widget>[
      EasyRefresh.custom(
      enableControlFinishRefresh: false,
        // 是否开启控制结束刷新
        enableControlFinishLoad: true,
        // 是否开启控制结束加载
        controller: _controller,
        // EasyRefresh控制器
//          header: ClassicalHeader(),
        header: ClassicalHeader(
          enableInfiniteRefresh: false,
          refreshText: "拉动刷新",
          refreshReadyText: "释放刷新",
          refreshingText: "正在刷新...",
          refreshedText: "刷新完成",
          refreshFailedText: "刷新失败",
          noMoreText: "没有更多数据",
          showInfo: false, // 是否显示时间
//            infoText: "更新于 %T",
        ),
//          footer: ClassicalFooter(),
        footer: ClassicalFooter(
          loadText: "拉动加载",
          loadReadyText: "释放加载",
          loadingText: "正在加载...",
          loadedText: "加载完成",
          loadFailedText: "加载失败",
          noMoreText: "没有更多数据",
          infoText: "更新于 %T",
        ),
        onRefresh: () async {
          print('onRefresh');
          pageIndex = 1;
          initHttpData();
//          await Future.delayed(Duration(seconds: 2), () {
//
//          });
        },
        onLoad: () async {
          print('onLoad');
          pageIndex++;
          initHttpData();
//          await Future.delayed(Duration(seconds: 2), () {
//
////            _controller.finishLoad(noMore: _count >= 40);
//          });
        },
        slivers: <Widget>[
          SliverList(
            delegate: SliverChildBuilderDelegate(
                  (context, index) {
                if (dataList != null && dataList.length > 0) {
                  return InkWell(
                    child: ItemToDoTaskView(context, dataList[index], index,"3"),
                    onTap: () {
                      showDialog(
                          context: context,
                          barrierDismissible: true,
                          builder: (_) {
                            return new LoadingDialog(text: "努力加载中");
                          });
                      setToDoNet(context,dataList[index],"3");

//                      String processInstanceId =
//                      dataList[index]["processInstanceId"];
//                      print("查看流程图processInstanceId:$processInstanceId");
//                      if (processInstanceId == null) {
//                        processInstanceId = "";
//                      }
//                      String url = GlobalUrl.WEB_CHART_URL +
//                          "?processInstanceId=" +
//                          processInstanceId +
//                          "&platform=app";
//                      Navigator.pushNamed(context, '/webViewUtilPage',
//                          // webViewUtilPage   WebViewExample
//                          arguments: {
//                            Global.WEBVIEW_TAG: Global.HIISTORYTASK,
//                            Global.WEBVIEW_URL: url,
//                          }).then((value) {
//                        //HELP
//                        print('webview:$value');
//                      });
                    },
                  );
                } else {
                  return Container(
                    height: TLSizeFit.screenHeight - TLSizeFit.setPx(200),
                    alignment: Alignment.center,
                    child: Center(
                      child: Text('还没有数据哦'),
                    ),
                    color: Colors.transparent,
                  );
                }
              },
//              childCount: dataList.length==0?1:dataList.length,
              childCount: dataList.length,
            ),
          ),
        ],
      ),
      (this.dataList.length <= 0 && !noDataflag) ? LoadingView() : Container(),

      noDataflag ? NoDataView(): Container(),


      ],
    ),);
  }

  /**
   * 没有数据的布局样式
   */
  Widget noDataView(){
    return Container(
      height: TLSizeFit.screenHeight - 200,
      alignment: Alignment.center,
      child: Center(
        child: Text('还没有数据哦'),
      ),
      color: Colors.transparent,
    );
  }

  initHttpData() async {
//    http://10.66.1.100:8181/api/us-process/process/pageFinished?current=1&size=10

    String apiUrlhttp = GlobalUrl.PROCESSTASK;
    var map = {
      "processDefinitionKeys": "projectCostSalesAuditProcess,projectCostSalesAuditProcess,projectCostDeliveryAuditProcess,projectInfoUpdateAuditProcess,projectDeliveryAheadAuditProcess,projectBasicInfoAuditProcess",
      "current": pageIndex,
      "size": "10",
    };
    String access_token = await Storage.getToken();
    LogUtil.init(title: "来自LogUtil", isDebug: false, limitLength: 800);
    var mapHeaders = {
      Global.AUTHORIZATION: access_token,
      Global.CONTENT_TYPE: Global.APPLICATION_JSON
    };
    HttpUtil.get(apiUrlhttp, data: map, headers: mapHeaders, success: (data) {
      // 下拉刷新停止
      _controller.resetLoadState();
      //  上拉加载停止
      _controller.finishLoadCallBack();
//    _controller.finishLoad(noMore: false);
      _controller.finishLoad();

      var success = data["success"];
//      LogUtil.v("success:$success");
      var message = data["msg"];
      var body = data["data"];
      var code = data["code"];
//      LogUtil.v("body:$body");
      if (success != null && success == true) {
        LogUtil.v("进来了...正式立项");
        List getList = body["records"];
//        LogUtil.v("getList:$getList");
        LogUtil.v("获取的接口数据集合：${getList.length}");

        if (pageIndex == 1) {
          dataList.clear();
          dataList.addAll(getList);
        } else {
          dataList.addAll(getList);
        }
        print("集合的长度:${dataList.length}");

        if (dataList.length == 0) {
          setState(() {
            noDataflag = true;
          });
        } else {
          setState(() {
            dataList = dataList;
            noDataflag = false;
          });
        }
      }
    }, error: (errorMsg) {
      print("待办任务..正式..errorMsg: $errorMsg");
      // 下拉刷新停止
      _controller.resetLoadState();

      //  上拉加载停止
      _controller.finishLoadCallBack();
//            _controller.finishLoad(noMore: false);
      _controller.finishLoad();
    });
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    print("正式立项.....dispose");
    _controller.dispose();
    //取消订阅
    eventBusRe.cancel();
  }
}
